#include "comm.h"

class Init
{
public:
    Init()
    {
        // 利用管道，来让共享内容同步
        bool r = MakeFifo();
        if (!r)
            return;
        // 1.获取Key
        key_t Key = GetKey();
        std::cout << "key : " << ToHex(Key) << std::endl;
        // 2.申请共享内存
        int shmid = CreatShm(Key);
        std::cout << "shmid: " << shmid << std::endl;
        std::cout << "开始将shm映射到进程的地址空间中" << std::endl;
        // 3.和共享内存建立映射
        s = (char *)shmat(shmid, nullptr, 0);
       fd = open(FILENAME.c_str(), O_RDONLY);
       
    }

    ~Init()
    {
        // 4.和共享内存解映射
        shmdt(s);
        std::cout << "开始将shm从进程的地址空间中移除" << std::endl;
        // 5.删除共享内存
        shmctl(shmid, IPC_RMID, nullptr);
        std::cout << "开始将shm从OS中删除" << std::endl;
        close(fd);
    }

public:
    int shmid;
    int fd;
    char *s;
};

int main()
{
    Init init;
    //通信：读数据
     sleep(5);
    while (true)
    {
        // wait
        int code = 0;
        ssize_t n = read(init.fd, &code, sizeof(code));
        if (n > 0)
        {
            // 直接读取的哦
            std::cout << "共享内存的内容: " << init.s << std::endl;
            sleep(1);
        }
        else if (n == 0)
        {
            break;
        }
    }

    return 0;
}
